<?php

/**
 * @Author: Bing
 * @Date:   2019-04-15 21:53:43
 * @Email:  huangfreeze@gmail.com
 * @Last Modified time: 2019-04-30 18:04:56
 */

use EasyWeChat\Foundation\Application;

/**
 * 微信功能
 */
class WechatMp
{
	/**
	 * 微信对象
	 */
	public $app;

	public function __construct() {

		$configObj = new Config("wechat_config");
		$options = $configObj->getInfo();

		$oauth = $this->getBackendWechatOauth();
		if ( count($oauth) ) {
			$config = unserialize(ArrayHelper::getValue($oauth, 'config'));
			$options['app_id'] = ArrayHelper::getValue($config, 'AppID_APP');
			$options['secret'] = ArrayHelper::getValue($config, 'AppSecret_APP');
		}
		$this->app = new Application($options);

	}

	/**
	 * 返回后台设置的微信信息
	 */
	public function getBackendWechatOauth()
	{
		$oauthDB = new IModel('oauth');
		$where   = "is_close = 0 and file = 'wechatOauth'";
		return $oauthDB->getObj($where);
	}

	public static function getApp()
	{
		$self = new WechatMp();
		return $self->app;
	}

	public static function getUserService()
	{
		$app = self::getApp();
		return $app->oauth->user();
	}

	/**
	 * 微信自动登录
	 */
	public static function wechatAutoLogin($wechatInfo)
	{
		$openid = ArrayHelper::getValue($wechatInfo, 'openid');
		if ( !$openid ) {
			return false;
		}

		$wechatModel = new IModel('wechat_user_info');
		$openidWhere = " openid = '{$openid}' ";
		$wechat = $wechatModel->getObj($openidWhere);

		/**
		 * 微信信息
		 */
		$data = array(
			'nickname'   => ArrayHelper::getValue($wechatInfo, 'nickname'),
			'sex'        => ArrayHelper::getValue($wechatInfo, 'sex'),
			'language'   => ArrayHelper::getValue($wechatInfo, 'language'),
			'city'       => ArrayHelper::getValue($wechatInfo, 'city'),
			'province'   => ArrayHelper::getValue($wechatInfo, 'province'),
			'country'    => ArrayHelper::getValue($wechatInfo, 'country'),
			'headimgurl' => ArrayHelper::getValue($wechatInfo, 'headimgurl'),
			'privilege'  => JSON::encode(ArrayHelper::getValue($wechatInfo, 'privilege')),
			'unionid'    => ArrayHelper::getValue($wechatInfo, 'unionid'),
			'updated_at' => ITime::getDateTime(),
		);

		/**
		 * 创建新微信用户
		 */
		if ( !count($wechat) ) {

			$data['openid'] = $openid;
			$data['created_at'] = ITime::getDateTime();

			$wechatModel->setData($data);
			if ( !$wechatModel->add() ) {
				return false;
			}
		}
		/**
		 * 更新微信信息
		 */
		else {
			$wechatModel->setData($data);
			if ( !$wechatModel->update($openidWhere) ) {
				return false;
			}
		}

		$nowWechat = $wechatModel->getObj($openidWhere);
		ISafe::set('wechat_openid', $openid);
		ISafe::set('wechat_nickname', ArrayHelper::getValue($nowWechat, 'nickname'));
		/**
		 * 自动登录
		 */
		$userId = ArrayHelper::getValue($nowWechat, 'user_id');
		if ( $userId ) {
			
			$userObj = new IModel('user as u,member as m');
			$where   = " u.id = '{$userId}' and m.status = 1 and u.id = m.user_id ";
			$userRow = $userObj->getObj($where);
			if ( count($userRow) ) {
				plugin::trigger('userLoginCallback', $userRow);
			}
			else {
				plugin::trigger('clearUser');
			}
		}
		/**
		 * 微信未绑定账号，但已登录账号，自动绑定
		 */
		else if ( !$userId && $loginUserId = ISafe::get('user_id') ) {
			$check = $wechatModel->getObj(" user_id = {$loginUserId} ");
			/**
			 * 当前登录账号未绑定微信
			 */
			if ( !count($check) ) {
				$updateWechat = new IModel('wechat_user_info');
				$updateWechat->setData(array('user_id' => $loginUserId));
				if ( !$updateWechat->update($openidWhere) ) {
					return false;
				}
			} else {
				plugin::trigger('clearUser');
			}
		}

		return true;
	}

	/**
	 * 登录后绑定微信
	 */
	public static function loginBindWechat()
	{
		$userId = ISafe::get('user_id');
		if ( !$userId ) {
			return false;
		}

		if ( !IClient::isWechat() || !ISafe::get('wechat_openid') ) {
			return false;
		}

		$openid = ISafe::get('wechat_openid');
		$openidWhere = " openid = '{$openid}' ";

		$wechatModel = new IModel('wechat_user_info');
		$userInfo = $wechatModel->getObj(" user_id = {$userId} ");
		/**
		 * 有绑定微信，绑定的微信与当前登录微信一样，返回true
		 */
		if ( count($userInfo) && ArrayHelper::getValue($userInfo, 'openid') == $openid ) {
			return true;
		}
		/**
		 * 有绑定微信，绑定的微信与当前登录微信不一样，返回false
		 */
		if ( count($userInfo) && ArrayHelper::getValue($userInfo, 'openid') != $openid ) {
			return false;
		}

		$userInfo = $wechatModel->getObj($openidWhere);
		if ( !count($userInfo) ) {
			return false;
		}

		/**
		 * 当前微信已绑定账号，但绑定的账号与当前账号不一致，返回false
		 */
		if ( ArrayHelper::getValue($userInfo, 'user_id') && ArrayHelper::getValue($userInfo, 'user_id') != $userId ) {
			return false;
		}
		/**
		 * 当前微信已绑定账号，但绑定的账号与当前账号一致，返回true
		 */
		if ( ArrayHelper::getValue($userInfo, 'user_id') && ArrayHelper::getValue($userInfo, 'user_id') == $userId ) {
			return true;
		}

		$wechatModel->setData(array('user_id' => $userId));
		if ( $wechatModel->update($openidWhere) ) {
			return true;
		}
		return false;
	}
}